package cn.bookCity.servlet;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import cn.bookCity.constant.Constant;
import cn.bookCity.domain.User;
import cn.bookCity.service.UserService;
import cn.bookCity.util.BeanFactory;
import cn.bookCity.util.MD5Utils;

@WebServlet("/manager/admin")
public class AdminServlet extends BaseServlet {
	
	public String admin(HttpServletRequest request,HttpServletResponse response)throws Exception {
		return "/adminLogin.jsp";
	}
	public String login(HttpServletRequest request,HttpServletResponse response)throws Exception {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String  pd=MD5Utils.md5(password);
		String checkcode=request.getParameter("checkcode");
		HttpSession session=request.getSession();
		String verificationCode=session.getAttribute("verificationCode").toString();
		UserService u=(UserService)BeanFactory.getBean("UserService");
		User user=u.login(username, pd);
		if(session.getAttribute("user")==null) {
			try {
				response.sendRedirect("home.htm");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;//直接结束方法 流程不在继续
		}
		if(!checkcode.equals(verificationCode)) {
			request.setAttribute("msg", "验证码不正确！");
			return "/adminLogin.jsp";
		}
		
		if(user==null) {
			request.setAttribute("msg", "用户名密码不正确");
			return "/adminLogin.jsp";
		}
		else {
			if(Constant.USER_IS_ACTIVE!=user.getState()) {
				request.setAttribute("msg", "用户没有被激活");
				return "/adminLogin.jsp";
			}
		}
		System.out.println(user.getEmail()+" "+user.getRole());
		if(!user.getRole().equals("超级用户")) {
			request.setAttribute("msg", "您不是超级用户，请到普通用户出登录~！");
			return "/adminLogin.jsp";
		}
		String autoLogin=request.getParameter("autoLogin");
		if(autoLogin!=null) {
			Cookie cookie=new Cookie("autologin",username+"-"+password);
			cookie.setMaxAge(Integer.parseInt(autoLogin));
            cookie.setPath(request.getContextPath());
			response.addCookie(cookie);
			
		}
		System.out.println("jjjjjjjjjjjj");
		request.getSession().setAttribute("user", user);
		response.sendRedirect(request.getContextPath()+"/manager/home.htm");
		return null;
	}

}
